package one.stand.controller;

import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.*;
import com.jmp.feign.GoodsFeign;
import com.jmp.feign.SeeRecordFeign;
import com.jmp.feign.TemplateFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Builder;
import lombok.Data;
import one.stand.advice.ResultEnum;
import one.stand.dto.Company2Dto;
import one.stand.dto.ConvertUtils;
import one.stand.mapper.GoodSpecMapperExt;
import one.stand.model.*;
import one.stand.service.*;
import one.stand.util.AssertUtil;
import one.stand.util.OneStringUtils;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "拼团")
@RequestMapping("goods/group")
@RestController
public class GoodsGroupController {
    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private TemplateFeign templateFeign;
    @Autowired
    private SeeRecordFeign seeRecordFeign;

    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private GoodSpecMapperExt goodSpecMapperExt;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private WebsiteService websiteService;

    @ApiOperation(value = "1:详情")
    @PostMapping("info")
    @SecurityAuthCheck
    public ResultModel<GoodsGroupInfoResponse> info(@RequestBody GoodsGroupInfoRequest request) {
        ResultModel<GoodsGroupInfoVo> resultModel = goodsFeign.groupInfo(GoodsGroupInfoDto.builder()
                .id(request.getGroupId())
                .build());
        AssertUtil.isTrue(resultModel);
        GoodsGroupInfoVo group = resultModel.getData();
        AssertUtil.isTrue(Objects.nonNull(group) && group.getStatus() == 1, ResultEnum.PARAM_CHECK, "活动已下架");
        Date now = new Date();
        long time = group.getEndTime().getTime() - now.getTime();
        AssertUtil.isTrue(time > 0, ResultEnum.PARAM_CHECK, "活动结束");
        Goods goods = goodsBaseService.get(group.getGoodsId());
        AssertUtil.isTrue(Objects.nonNull(goods) && goods.getIsDel() == 0, ResultEnum.PARAM_CHECK, "商品已下架");

        //商品规格
        GoodSpecModel specModel = new GoodSpecModel();
        specModel.setGoodsId(goods.getGoodsId());
        specModel.setIsDel(0);
        List<GoodSpecModel> specModelList = goodSpecMapperExt.getSpec(specModel);
        List<GoodsGroupInfoResponse.Spec> goodSpecModelList = ConvertUtils.list(specModelList, goodSpecModel -> GoodsGroupInfoResponse.Spec.builder()
                .specId(goodSpecModel.getSpecId())
                .specName(goodSpecModel.getSpecName())
                .goodSpecModelList(ConvertUtils.list(goodSpecModel.getGoodSpecModelList(), spec -> GoodsGroupInfoResponse.Spec.builder()
                        .specId(spec.getSpecId())
                        .specName(StringUtils.isNoneBlank(spec.getSpecAttribute()) ? spec.getSpecAttribute() : spec.getSpecName())
                        .build()))
                .build());

        BusinessCard card = businessCardBaseService.getCustomer(request.getCardId());
        AssertUtil.nonNull(card, ResultEnum.PARAM_CHECK, "名片不存在");
        Company2Dto companyModel = companyBaseService.get2(card.getCompanyId());
        //公司地址
        Website websiteModel = websiteService.getByCompanyId(card.getCompanyId());
        //分享人海报
        TemplateGet2Request createRequest = TemplateGet2Request.builder()
                .templateType(TemplateApi.Type.ID_ARTICLE_H5_WXCODE)
                .cardId(card.getCardId())
                .build();
        ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(createRequest);
        AssertUtil.isTrue(getResponseResultModel);

        BigDecimal price = Objects.nonNull(request.getPrice()) ? request.getPrice() : goods.getRetailPrice();
        String shareH5Url = goodsBaseService.getGroupShareH5Url(request.getCardId(), request.getGroupId(), String.valueOf(price));

        if (!RequestContextHolder.getRequestContext().isSameCard(request.getCardId())) {//添加查看记录
            final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
            SeeRecordGoodsRequest recordGoodsRequest = SeeRecordGoodsRequest.builder()
                    .userId(optUser.getUserId())
                    .cardId(request.getCardId())
                    .companyId(goods.getCompanyId())
                    .itemId(goods.getGoodsId())
                    .type(1)
                    .groupId(request.getGroupId())
                    .build();
            seeRecordFeign.goods(recordGoodsRequest);
        }

        GoodsGroupInfoResponse response = GoodsGroupInfoResponse.builder()
                .groupId(group.getId())
                .startTime(group.getStartTime().getTime())
                .time(group.getEndTime().getTime())
                .videoUrl(group.getVideoUrl())

                .goodsId(goods.getGoodsId())
                .goodsName(goods.getGoodsName())
                .goodsPhotos(goodsPhotoService.getListPath(goods.getGoodsId()))
                .goodsVideo(goods.getVideoUrl())
                .goodsDetails(goods.getGoodsDetails())
                .goodSpecModelList(goodSpecModelList)

                .cardId(card.getCardId())
                .cardImg(card.getLogo())
                .cardName(card.getName())
                .cardPosition(card.getPosition())
                .cardPhone(card.getPhone())
                .cardUrl(getResponseResultModel.getData().getImageUrl())
                .companyName(companyModel.getCompanyName())
                .companyAddr(Objects.nonNull(websiteModel) ? websiteModel.getAddress() : null)
                .latitude(Objects.nonNull(websiteModel) ? websiteModel.getLatitude() : null)
                .longitude(Objects.nonNull(websiteModel) ? websiteModel.getLongitude() : null)

                .shareTitle(group.getTitle())
                .shareSubTitle(group.getTitle())
                .shareImg(OneStringUtils.photoResizeShareH5(group.getPhoto()))
                .shareUrl(shareH5Url)
                .build();
        return ResultModel.success(response);
    }

    @Data
    public static class GoodsGroupInfoRequest {
        private Integer groupId;
        private Integer cardId;
        @ApiModelProperty("用户自定义零售价")
        private BigDecimal price;
    }

    @Data
    @Builder
    public static class GoodsGroupInfoResponse {
        @ApiModelProperty("ID")
        private Integer groupId;
        @ApiModelProperty("开始时间(时间戳|毫秒)")
        private Long startTime;
        @ApiModelProperty("结束时间(时间戳|毫秒)")
        private Long time;
        @ApiModelProperty("视频介绍")
        private String videoUrl;

        @ApiModelProperty("商品ID")
        private Integer goodsId;
        @ApiModelProperty("商品视频")
        private String goodsVideo;
        @ApiModelProperty("商品图片,多张逗号分割")
        private List<String> goodsPhotos;
        @ApiModelProperty("商品名称")
        private String goodsName;
        @ApiModelProperty("商品详情")
        private String goodsDetails;
        @ApiModelProperty(value = "规格", dataType = "GoodsGroupInfoResponse.Spec")
        private List<Spec> goodSpecModelList;

        private Integer cardId;
        private String cardImg;
        private String cardName;
        private String cardPosition;
        private String cardPhone;
        private String cardUrl;
        private String companyName;
        private String companyAddr;
        /**
         * 坐标
         */
        private String latitude;
        private String longitude;

        @ApiModelProperty("h5分享-标题")
        private String shareTitle;
        @ApiModelProperty("h5分享-描述")
        private String shareSubTitle;
        @ApiModelProperty("h5分享-地址")
        private String shareUrl;
        @ApiModelProperty("h5分享-图片")
        private String shareImg;

        @ApiModel("GoodsGroupInfoResponse.Spec")
        @Data
        @Builder
        public static class Spec {
            private Integer specId;
            private String specName;
            @ApiModelProperty(value = "规格", dataType = "GoodsGroupInfoResponse.Spec")
            private List<Spec> goodSpecModelList;
        }
    }
}
